#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include"mystdio.h"
#include<unistd.h>
MY_FILE* my_fopen(const char* path, const char* mode)
{
  int flag = 0;
  if(strcmp(mode,"r") == 0)
  {
    flag|= O_RDONLY;
  }
  if(strcmp(mode,"w") == 0)
  {

    flag|= O_WRONLY | O_CREAT | O_TRUNC;
  }

  if(strcmp(mode,"a") == 0)
  {
  
    flag|= O_WRONLY | O_CREAT | O_APPEND;
  }

  mode_t m = 0666;
  int fd = 0;
  if((flag & O_CREAT))
  {

    fd = open(path,flag,m);
  }
  else
  {
    fd = open(path,flag);
  }
  if(fd == -1)
  {
    return NULL;
  }
  MY_FILE* fp = (MY_FILE*)malloc(sizeof(MY_FILE));
  fp->fd=fd;
  memset(fp->buffer,'\0',sizeof(fp->buffer));
  fp->count = 0;
  return fp;
}

int my_fclose(MY_FILE* fp)
{
  

  my_fflush(fp);
  free(fp);



  return 0;
}

size_t my_write(const void* ptr,size_t size,size_t count,MY_FILE* fp)
{
  if(fp->count ==BUFMAX)
  {
    my_fflush(fp);
  }
  size_t pushsize = size * count;
  size_t mysize = BUFSIZ - fp->count;
  if(mysize >= pushsize)
  {
    memcpy(fp->buffer+fp->count,ptr,pushsize);
    fp->count += pushsize;
    return pushsize;
  }
  else
  {
    memcpy(fp->buffer+fp->count,ptr,mysize);
    fp->count+=mysize;
    return mysize;
  }
}
int my_fflush(MY_FILE* fp)
{
  write(fp->fd,fp->buffer,fp->count);
  fp->count = 0;
  fsync(fp->fd);
  return 0;
}


size_t my_read(void* ptr,size_t size,size_t count,MY_FILE* fp)
{
    ssize_t rnum = read(fp->fd,ptr,size*count);
  
    return rnum;
}
